package cn.pzaily.fealetter.service.impl;

import cn.pzaily.crab.tools.core.utils.ObjectUtils;
import cn.pzaily.crab.tools.core.utils.StringUtils;
import cn.pzaily.fealetter.entity.ConfigTemplateEntity;
import cn.pzaily.fealetter.entity.TemplateEntity;
import cn.pzaily.fealetter.enumeration.RedisPropertiesKey;
import cn.pzaily.fealetter.mapper.ConfigTemplateMapper;
import cn.pzaily.fealetter.mapper.TemplateMapper;
import cn.pzaily.fealetter.service.TemplateService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

/**
 * @PackageName: cn.pzaily.fealetter.service.impl
 * @Description:
 * @Author: Pang
 * @Date: 2021-11-23 21:25
 */
@Service
public class TemplateServiceImpl extends ServiceImpl<TemplateMapper, TemplateEntity> implements TemplateService {

    private RedisTemplate redisTemplate;

    private ConfigTemplateMapper configTemplateMapper;

    public TemplateServiceImpl(RedisTemplate redisTemplate, ConfigTemplateMapper configTemplateMapper) {
        this.redisTemplate = redisTemplate;
        this.configTemplateMapper = configTemplateMapper;
    }

    @Override
    public TemplateEntity findTemplateByCode(String code) {
        ValueOperations<String, TemplateEntity> ops = redisTemplate.opsForValue();
        TemplateEntity templateEntity = ops.get(code);
        if (ObjectUtils.isNull(templateEntity)) {
            templateEntity = baseMapper.selectOne(new LambdaQueryWrapper<TemplateEntity>()
                    .eq(TemplateEntity::getCode, code));
            if (ObjectUtils.isNotNull(templateEntity)) {
                ops.set(code, templateEntity, RedisPropertiesKey.TIME, RedisPropertiesKey.TIME_UNIT);
            }
        }
        return templateEntity;
    }

    @Override
    public String findConfigCodeByCode(String id, String template) {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String templateCode = ops.get(template + "_" + id + "code");
        if (StringUtils.isEmpty(templateCode)) {
            TemplateEntity templateByCode = findTemplateByCode(templateCode);

            ConfigTemplateEntity configTemplateEntity =
                    configTemplateMapper.selectOne( new LambdaQueryWrapper<ConfigTemplateEntity>()
                            .eq(ConfigTemplateEntity::getId, id)
                            .eq(ConfigTemplateEntity::getTemplateId, templateByCode));
            templateCode = ObjectUtils.isNotNull(configTemplateEntity) ? configTemplateEntity.getConfigTemplateCode() : "";
            ops.set(template + "_" + id + "code", templateCode, RedisPropertiesKey.TIME, RedisPropertiesKey.TIME_UNIT);
        }
        return templateCode;
    }
}
